//
//  LQBigPictureViewCell.swift
//  weiboLQ
//
//  Created by 半缘君 on 15/12/18.
//  Copyright © 2015年 banyuanjun.cn. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

protocol LQPhotoBrowserViewCellDelegate:NSObjectProtocol {
    //图片恢复原来的位置
    func photoBrowserViewDidTapToMiss()
    //根据alpha设置视图的透明度
    func photoBrowserViewDidScale(scale:CGFloat)
}


class LQPhotoBrowserViewCell: UICollectionViewCell {
    
    var photoDelegate:LQPhotoBrowserViewCellDelegate?
    
    var imageURl:NSURL? {
        didSet {
            //getBmiddleURL(imageURl!)
            
            resetScrollView()
            
            let placeholderImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(imageURl?.absoluteString)
            
//            placehoder.image = placeholderImage
//            placehoder.sizeToFit()
//            placehoder.center = scrollView.center
            
            setPlacehoder(placeholderImage)
            //SDWebImageOptions.RetryFailed, SDWebImageOptions.RefreshCached
            imageV.sd_setImageWithURL(getBmiddleURL(imageURl),
                placeholderImage: nil,
                options: [],
                progress: { (current, total) -> Void in
                    
//                     print(NSThread.currentThread())
//                    print(CGFloat(current) / CGFloat(total))
                    // 更新进度
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.placehoder.progress = CGFloat(current) / CGFloat(total)
                    })
                    
                }) { (image, _, _, _) -> Void in
                    
                    // 判断图像下载是否成功
                    if image == nil {
                        SVProgressHUD.showInfoWithStatus("您的网络不给力")
                        
                        return
                    }
                    
                    // 隐藏占位图像
                    self.placehoder.hidden = true
                    
                    // 设置图像视图位置
                    self.setPositon(image)
            }
//
//            
        }
    }
    //设置占位视图
    private func setPlacehoder (image:UIImage) {
        self.placehoder.hidden = false
        placehoder.image = image
        placehoder.sizeToFit()
        placehoder.center = scrollView.center
    }
//    private func setPosition (imageV:UIImageView) {
//        imageV.frame.size = displaySize(imageV)
//        imageV.frame.origin = CGPointZero
        private func setPositon(image: UIImage) {
            // 自动设置大小
            let size = self.displaySize(image)
            
            // 判断图片高度
            if size.height < scrollView.bounds.height {
                // 上下局中显示 - 调整 frame 的 x/y，一旦缩放，影响滚动范围
                imageV.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
                
                // 内容边距 － 会调整控件位置，但是不会影响控件的滚动
                let y = (scrollView.bounds.height - size.height) * 0.5
                scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
            } else {
                imageV.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
                scrollView.contentSize = size
            }
        }
//    }
    
    //缩放图片
//    private func displaySize (imageV:UIImageView) -> CGSize {
//        let size = imageV.bounds.size
//        let w = UIScreen.mainScreen().bounds.width
//        let h = size.height * w / size.width
//        return CGSizeMake(w, h)
//        
//        
//    }
    private func displaySize(image: UIImage) -> CGSize {
        
        let w = scrollView.bounds.width
        let h = image.size.height * w / image.size.width
        
        return CGSize(width: w, height: h)
    }
    ///  获得中图
    private func getBmiddleURL(thumbURL:NSURL?) -> NSURL {
    var urlString = imageURl?.absoluteString// as NSString
    urlString = urlString?.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        return NSURL(string: urlString!)!
    }

    
    private func resetScrollView () {
//        scrollView.contentOffset = CGPointZero
        imageV.transform = CGAffineTransformIdentity
        
        // 重设 scrollView 的内容属性
        scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    //MARK: - 构造方法
    override init(frame: CGRect) {
       let frame = UIScreen.mainScreen().bounds
        super.init(frame: frame)
        
        setupUI ()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

        /// scrollView使得图片能够滚动和缩放
        lazy var scrollView:UIScrollView = UIScrollView()
        //imageView存放图片
        lazy var imageV:UIImageView = UIImageView()
        //占位图片
        private lazy var placehoder:LQProgressImageView = LQProgressImageView()
    
    private func setupUI () {
        addScrollView()
        scrollView.addSubview(imageV)
//       imageV.userInteractionEnabled = true
        scrollView.addSubview(placehoder)
        
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        imageV.userInteractionEnabled = true
        imageV.addGestureRecognizer(tap)
       
    }
    
    
        private func addScrollView () {
            contentView.addSubview(scrollView)
            let rect = bounds
//            rect.size.width -= 20
            scrollView.frame = rect
//            print("ScrollView  \(scrollView.frame)")
//            scrollView.backgroundColor = UIColor.grayColor()
            scrollView.delegate = self
            scrollView.maximumZoomScale = 2.0
            scrollView.minimumZoomScale = 0.5
        }


    }

extension LQPhotoBrowserViewCell:UIScrollViewDelegate {
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageV
    }
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        if scale < 1{
            self.photoDelegate?.photoBrowserViewDidTapToMiss()
        }
        
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        
        offsetY = offsetY < 0 ? 0 : offsetY
        
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        offsetX = offsetX < 0 ? 0 : offsetX
        
        // 设置间距
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    }
    //正在滚动
    func scrollViewDidZoom(scrollView: UIScrollView) {
//imageV.transform.a 缩放比例
        self.photoDelegate?.photoBrowserViewDidScale(imageV.transform.a)
    }
}

extension LQPhotoBrowserViewCell {
    func tapImage () {
        self.photoDelegate?.photoBrowserViewDidTapToMiss()
    }
}

